<?php

/**
 * PropertyController
 * 
 * @author Martin Bianculli
 * @version 0.1
 */
require_once 'Zend/Controller/Action.php';

class PropertyController extends Zend_Controller_Action {   

    public function init() {
        $ajax_actions = array('load', 'marker', 'search');
        if (in_array($this->getRequest()->getActionName(), $ajax_actions)) {
            if (!$this->getRequest()->isXmlHttpRequest()) throw new Exception('Invalid method'); 
        }        
        $ajaxContext = $this->_helper->getHelper('AjaxContext');
        foreach ($ajax_actions as $ajax_action) $ajaxContext->addActionContext($ajax_action, 'json');
        $ajaxContext->initContext();        
    }
    
    public function indexAction() {
        $id = $this->getRequest()->getParam('id', null);
        $property = Model_Property::find($id);
        $this->view->property = $property;
        $this->view->image_path = Model_Image::getPath();
                
        $this->view->headScript()->appendFile('/js/galleria-1.2.4.min.js');
        $this->view->headScript()->appendFile('/js/galleria.classic.js');
    }
    
    /**
     * Return a Json structure with all the properties in the DB
     */
    public function loadAction() {
    	$this->setMarkers(Model_Property::find());   	    	
    }
    
    /**
     * 
     * Return a Json structure with the information of an specific property
     */
    public function markerAction() {
        $id = $this->getRequest()->getPost('id');
        $property = Model_Property::find($id);
        if ($property) {
            $this->view->desc = $property->desc;
            $this->view->id = $property->id;
        }        
    } 
    
    /**
     * 
     * Return a Json structure with the properties matching the search criteria
     */
    public function searchAction() {
    	$this->setMarkers(Model_Property::filter($this->getRequest()->getPost()));        
    }
    
    private function setMarkers($properties) {
        $markers = array();
        foreach ($properties as $property) {
    		$markers[] = array(
    			'lat' => $property->coord->getLatitude(), 
    			'lng' => $property->coord->getLongitude(),
    			'id' => $property->id,
    		);    		
    	}
    	$this->view->markers = $markers;        
    }
    
}
